package com.nebula.dao.impl;

import com.nebula.entity.Navigation;
import com.nebula.dao.Database;
import com.nebula.dao.IMenuDao;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

/**
 * @author CcccX
 * @create 2019-01-11 16:05
 */
public class MenuDaoImpl extends BaseDaoImpl<Navigation> implements IMenuDao {
    @Override
    public List<Navigation> selectByRoleId(int roleId) {
        List<Navigation> list = new ArrayList<>();
        String sql = "SELECT * FROM navigation WHERE id in (SELECT nav_id FROM role_navigation WHERE role_id = ?) ORDER BY" +
                " sort ASC";
        ResultSet rs = (ResultSet) Database.excute(sql, roleId);
        try {
            if (rs != null) {
                setNavigation(list, rs);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return list;
    }

    @Override
    public List<Navigation> selectParentNode(int roleId) throws SQLException {
        List<Navigation> list = new ArrayList<>();
        String sql = "SELECT * FROM navigation WHERE parent_id = '0' and id in (SELECT nav_id FROM " +
                "role_navigation " +
                "WHERE role_id = ?) ORDER BY sort ASC";
        ResultSet rs = (ResultSet) Database.excute(sql, roleId);
        if (rs != null) {
            setNavigation(list, rs);
        }
        return list;
    }

    @Override
    public List<Navigation> selectLevel2(int roleId, String parentId) throws SQLException {
        List<Navigation> list = new ArrayList<>();
        String sql = "SELECT * FROM navigation WHERE parent_id = ? and id in (SELECT nav_id FROM role_navigation " +
                "WHERE role_id = ?) ORDER BY sort ASC";
        ResultSet rs = (ResultSet) Database.excute(sql, new Object[]{parentId, roleId});
        if (rs != null) {
            setNavigation(list, rs);
        }
        return list;
    }

    private void setNavigation(List<Navigation> list, ResultSet rs) throws SQLException {
        while (rs.next()) {
            Navigation navigation = new Navigation();
            navigation.setId(rs.getString("id"));
            navigation.setItem(rs.getString("item"));
            navigation.setInstruction(rs.getString("instruction"));
            navigation.setIcon(rs.getString("icon"));
            navigation.setParentId(rs.getString("parent_id"));
            navigation.setUrl(rs.getString("url"));
            navigation.setSort(rs.getInt("sort"));
            navigation.setCreatedTime(rs.getTimestamp("created_time"));
            navigation.setUpdatedTime(rs.getTimestamp("updated_time"));
            list.add(navigation);
        }
    }
}
